<?php
// Initialisation
require('inc/init.inc.php');
require(PATH.'/class/gestion/mailings.class.php');

class MailingExport extends Mailing{
	
function Pdf(){
	$pdf=new MonFPDF();
	$adresse = '';
	if ($result=$this->db->query("SELECT adresse FROM config")){
		if ($row=$result->fetch_assoc())
			$adresse = $row['adresse'];
		$result->Close();
	}
	$pdf->SetFont('Arial','',10);
	$contact = '';
	$sql = "SELECT con_nom, con_prenom, con_titre, cli_nom, cli_adresse, cli_codepostal, cli_ville, cli_boitepostale
			FROM contacts
			JOIN clients ON clients.cli_id=contacts.con_cli_id
			JOIN envois ON envois.env_con_id=contacts.con_id
			WHERE env_envoi=1 AND env_mai_id={$this->cle()}";
	
	if ($result=$this->db->query($sql))
		while ($row=$result->fetch_assoc()){
			$pdf->AddPage();
			$contact = $row['cli_nom']."\nà l'attention de ".$row['con_titre']." ".$row['con_nom']."\n".$row['cli_adresse']."\n".$row['cli_codepostal']." ".$row['cli_ville'];
			$pdf->Image('perso/logo.jpg');
			$pdf->MultiCell(95, 5, utf8_decode($adresse), 0);
			$pdf->SetY(30);
			$pdf->SetXrel(50);
			$pdf->MultiCell(95, 5, utf8_decode($contact), 0);
			$pdf->SetY(60);
			$pdf->SetXrel(0);
			$pdf->WriteHtml(utf8_decode($this->attribut['mai_texte']));			
		}
	
	$pdf->Output($this->attribut['mai_titre'],'D');				
}

function Mail($test=false){
	
	// Obtention de l'adresse d'expedition
	$from = '';
	if ($result=$this->db->query("SELECT email FROM config")){
		if ($row=$result->fetch_assoc())
			$from = $row['email'];
		$result->Close();
	}
	if (!$from)
		return False;
	
	// Creation du délimiteur
	$delimiteur = "-----=".md5(uniqid(rand()));
	
	// Sujet du message
	$subject = $this->attribut['mai_objet'];
	
	// Recherche des fichiers joints
	$contient_fichier=False;
	if ($this->attribut['mai_fichier']!=''){
		$fichiers = name2files($this->attribut['mai_fichier'], 'upload/');			
		if (count($fichiers)>0) {
			$contient_fichier = True;
		}
		foreach	($fichiers as $key=>$value)
			$fichiers[$key] = str_replace('upload/','',$fichiers[$key]);
	}
	
	// Initialisation du message
	$msg = '';
	$entete = '';
			
	// mail avec fichier
	if ($contient_fichier){
		// Construction de l'entête
		$entete .= "MIME-Version: 1.0\r\n";
		$entete .= "Content-Type: multipart/related; boundary=\"$delimiteur\"\r\n";
		$entete .= "\r\n";
		// Message pour les clients ne supportant pas ce MIME
		$msg .= "Message au format MIME 1.0 multipart/mixed.\r\n";
		// Le code HTML
		$msg .= "--$delimiteur\r\n";
		$msg .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
		$msg .= "Content-Transfer-Encoding:8bit\r\n";
		$msg .= "\r\n";
		$msg .= "<html><body>";
		// Ajouts des balises images
		foreach	($fichiers as $key=>$value){
			if ( $key!=0 ) {
				$msg .= "<img src=\"cid:image$key\"><br />";
			}
		}
		$msg .= "</body></html>\r\n";
		$msg .= "\r\n";
		// Insertion des fichiers
		foreach	($fichiers as $key=>$value){
			if ( $key!=0 ) {
				$file = "upload/$value";
				$fp = fopen($file, "rb");
				$contenu_fichier = fread($fp, filesize($file));
				fclose($fp);
				$fichierattache = chunk_split(base64_encode($contenu_fichier));
				$msg .= "--$delimiteur\r\n";
				$msg .= "Content-Type: application/octet-stream; name=\"image$key.jpg\"\r\n";
				$msg .= "Content-Transfer-Encoding: base64\r\n";
				$msg .= "Content-ID: <image$key>\r\n";
				$msg .= "\r\n";
				$msg .= $fichierattache."\r\n";
				$msg .= "\r\n\r\n";
			}
		}
	}
	
	// mail avec texte
	else{
		$entete = "MIME-Version: 1.0\r\n";
		$entete .= "Content-Type: multipart/related; boundary=\"$delimiteur\"\r\n";
		$entete .= "\r\n";
		// Message HTML
		$msg .= "--$delimiteur\r\n";
		$msg .= 'Content-type: text/html; charset=utf-8'."\r\n\r\n";
		$msg .= $this->attribut['mai_texte']."\r\n\r\n";
	}
	
	// Pieces jointes
	foreach($this->attribut['mai_attachment'] as $att){
		$file = "upload/attachment/$att";
		
		$fp      = fopen($file, "rb");
		$fichier = fread($fp, filesize($file));
		fclose($fp);
		$fichierattache = chunk_split(base64_encode($fichier));
		
		$file_type = mime_content_type($file);
		
		$msg .= "--$delimiteur\r\n";
		$msg .= "Content-Type: $file_type; name=\"$att\"\r\n";
		$msg .= "Content-Transfer-Encoding: base64\r\n";
		$msg .= "Content-Disposition:attachement; filename=\"$att\"\r\n";
		$msg .= "\r\n";
		$msg .= $fichierattache . "\r\n";
		$msg .= "\r\n\r\n";
	}

	// Obtention des expediteurs
	$destinataires = Array();
	if ($test){
		$sql = "SELECT email_admin as email FROM config";
		if ($result=$this->db->query($sql))
			while ($row=$result->fetch_assoc())
				$destinataires = split(',',$row['email']);
	}
	else{
		$sql = "SELECT con_email as email
				FROM contacts
				JOIN clients ON clients.cli_id=contacts.con_cli_id
				JOIN envois ON envois.env_con_id=contacts.con_id
				WHERE env_envoi=1 AND env_mai_id={$this->cle()}";
		if ($result=$this->db->query($sql))
			while ($row=$result->fetch_assoc())
				$destinataires[] = $row['email'];

	}
	echo "envoi<br/>\n";
	foreach	($destinataires as $destinataire){
		$expediteur   = $from;
		$reponse      = $expediteur;
		$ok='ECHEC: ';
		if (mail($destinataire,
				 $subject,
				 $msg,
				 "Reply-to: $reponse\r\nFrom: $expediteur\r\n".$entete))
			$ok='OK: ';
		echo "$ok$destinataire<br/>\n";				 					
	}
}
}

// Lecture du mode: email, postal ou emailtest
$mode = get_param('mode', '');
// Lecture de l'id mysql du mailing
$id = get_param('id', 0);

$c = new MailingExport($db);
$c->Lire($id);
switch ($mode){
	case 'postal':
		$c->Pdf();
		break;
	case 'emailtest':
		$c->Mail(true);
		break;	
	case 'email':
		$c->Mail();
		break;	
}
?>
